<template>
  <div>
    <!-- 按钮 -->
    <el-button style="margin:10px 10px" type="primary" icon="el-icon-refresh-right" circle
      @click="list = []"></el-button>
    <!-- <el-button type="primary" @click="add">添加</el-button> -->
    <!-- <el-button type="primary" @click="deleteGoldTable(18)">删除</el-button> -->
    <!-- 表格
      data 展示数据 —— 数组类型
    -->
    <el-button @click="handleExport2" style="margin-right: 30px;">导出报表</el-button>
    <!-- <el-date-picker v-model="valueData" value-format="yyyy-MM-dd" type="daterange" align="right" unlink-panels
      range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
    </el-date-picker> -->
    <el-date-picker value-format="yyyy-MM" v-model="valueData" type="month" placeholder="选择月">
    </el-date-picker>
    <el-button style="margin-left: 10px;" icon="el-icon-search" @click="rangeChange"></el-button>
    <el-table id="table" style="width: 100%;" border :data="list">
      <el-table-column prop="id" label="id" align="center">
      </el-table-column>
      <el-table-column prop="month" label="日期" align="center">
      </el-table-column>
      <el-table-column label="充值类型" align="center">
        <template slot-scope="{ row, $index }">
          <p v-if="row.type == 1">充值金币</p>
          <p v-else-if="row.type == 2">购买广告</p>
          <p v-else-if="row.type == 3">充值会员</p>
        </template>
      </el-table-column>
      <el-table-column prop="rechargeMoney" label="充值金额" align="center">
      </el-table-column>
      <el-table-column prop="rechargeGold" label="充值金币(含赠送)" align="center">
      </el-table-column>

      <el-table-column prop="wxRate" label="微信手续费" align="center">
      </el-table-column>
      <el-table-column prop="alipayRate" label="支付宝手续费" align="center">
      </el-table-column>
      <el-table-column prop="iosRate" label="苹果手续费" align="center">
      </el-table-column>

      <!-- <el-table-column prop="totalGold" label="总金币" align="center">
      </el-table-column> -->
      <el-table-column prop="usableGold" label="本月可摊销金币" align="center">
      </el-table-column>
      <el-table-column prop="usableMoney" label="本月可摊销金额" align="center">
      </el-table-column>
      <el-table-column prop="usableRate" label="本月摊销率" align="center">
      </el-table-column>
      <el-table-column prop="useGold" label="本月已核销金币" align="center">
      </el-table-column>
      <el-table-column prop="useMoney" label="本月已核销金额" align="center">
      </el-table-column>
      <el-table-column prop="totalUnuseMoney" label="累计未核销金额" align="center">
      </el-table-column>
      <el-table-column prop="totalUnuseGold" label="累计未核销金币" align="center">
      </el-table-column>
   <!--   <el-table-column label="操作" align="center">
        <template slot-scope="{ row, $index }">
          <el-popconfirm title="是否删除？" icon="el-icon-info" icon-color="red" @confirm="deleteGoldTable(row.id)">
            <el-tooltip content="删除" placement="top" slot="reference">
              <el-button type="danger" icon="el-icon-delete"></el-button>
            </el-tooltip>
          </el-popconfirm>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 添加对话框  -->
    <el-dialog title="添加" :visible.sync="dialogFormVisible1">
      <el-form style="width:80%" :model="list1" ref="ruleForm">
        <el-form-item label="月份" label-width="120px" prop="month">
          <el-input autocomplete="off" v-model="list1.month"></el-input>
        </el-form-item>
        <el-form-item label="充值类型" label-width="120px">
          <el-select v-model="list1.type" placeholder="请选择充值类型" prop="type">
            <el-option label="充值金币" value="1"></el-option>
            <el-option label="购买广告" value="2"></el-option>
            <el-option label="充值会员" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值金额" label-width="120px" prop="rechargeMoney">
          <el-input autocomplete="off" v-model="list1.rechargeMoney"></el-input>
        </el-form-item>
        <el-form-item v-show="list1.type == 1" label="充值金币(含赠送)" label-width="120px" prop="rechargeGold">
          <el-input autocomplete="off" v-model="list1.rechargeGold"></el-input>
        </el-form-item>
        <el-form-item label="微信手续费" label-width="120px" prop="totalGold">
          <el-input autocomplete="off" v-model="list1.wxRate"></el-input>
        </el-form-item>
        <el-form-item label="支付宝手续费" label-width="120px" prop="totalGold">
          <el-input autocomplete="off" v-model="list1.alipayRate"></el-input>
        </el-form-item>
        <el-form-item label="苹果手续费" label-width="120px" prop="totalGold">
          <el-input autocomplete="off" v-model="list1.iosRate"></el-input>
        </el-form-item>
        <!-- <el-form-item v-show="list1.type == 1" label="总金币" label-width="120px" prop="totalGold">
          <el-input autocomplete="off" v-model="list1.totalGold"></el-input>
        </el-form-item> -->
        <el-form-item v-show="list1.type == 1" label="本月可摊销金币" label-width="120px" prop="usableGold">
          <el-input autocomplete="off" v-model="list1.usableGold"></el-input>
        </el-form-item>
        <el-form-item label="本月可摊销金额" label-width="120px" prop="usableMoney">
          <el-input autocomplete="off" v-model="list1.usableMoney"></el-input>
        </el-form-item>
        <el-form-item v-show="list1.type == 1" label="本月摊销率" label-width="120px" prop="usableRate">
          <el-input autocomplete="off" v-model="list1.usableRate"></el-input>
        </el-form-item>
        <el-form-item v-show="list1.type == 1" label="本月已核销金币" label-width="120px" prop="useGold">
          <el-input autocomplete="off" v-model="list1.useGold"></el-input>
        </el-form-item>
        <el-form-item label="本月已核销金额" label-width="120px" prop="useMoney">
          <el-input autocomplete="off" v-model="list1.useMoney"></el-input>
        </el-form-item>
        <el-form-item label="累计未核销金额" label-width="120px" prop="totalUnuseMoney">
          <el-input autocomplete="off" v-model="list1.totalUnuseMoney"></el-input>
        </el-form-item>
        <el-form-item v-show="list1.type == 1" label="累计未核销金币" label-width="120px" prop="totalUnuseGold">
          <el-input autocomplete="off" v-model="list1.totalUnuseGold"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="addGold">提交</el-button>
      </div>
    </el-dialog>
    <!-- 分页 -->
    <el-pagination style="margin-top:20px;textAlign:center" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page="pageNumber" :page-sizes="[10, 50, 100]" :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    exportToExcel
  } from '@/utils/Export2Excel'
  export default {
    name: 'goldCase',
    data() {
      return {
        dialogFormVisible1: false,
        valueData: [],
        //页码
        pageNumber: 1,
        //每页数量
        pageSize: 10,
        //总条数
        total: 0,
        //列表数据
        list: [],
        list1: {},
      }
    },
    mounted() {
      // 获取当前时间
      const today = new Date();
      // 获取当前时间(today)的年份
      const year = today.getFullYear();
      // 获取月份
      const month = String(today.getMonth() + 1).padStart(2, '0');
      // // 获取当前日
      // const day = String(today.getDate()).padStart(2, '0');
      // // 得到年月日
      // const thisDayDate = `${year}-${month}-${day}`; //打印当前日期
      console.log(year, month)
      // let ym = year + '-' + month
      // this.valueData[0] = ym + '-' + '01'
      // this.valueData[1] = ym + '-' + this.getLastDayOfMonth(year, month)
      // console.log(this.valueData)
      // this.getPageAccountDetailList()
    },
    methods: {
      async deleteGoldTable(id) {
        let res = await this.$API.running.deleteGoldTable({
          id,
        })
        console.log('金币删除', res)
        this.rangeChange()
      },
      toPercent(point) {
        var str = Number(point * 100).toFixed(2);
        str += "%";
        return str;
      },
      // 添加一条数据窗口弹出
      add() {
        // this.state = true
        this.dialogFormVisible1 = true
        this.list1 = {
          // month: "",
          // rechargeGold: "",
          // rechargeMoney: "",
          // totalGold: "",
          // totalUnuseGold: "",
          // totalUnuseMoney: "",
          // usableGold: "",
          // usableMoney: "",
          // usableRate: "",
          // useGold: "",
          // useMoney: '',
        }
      },
      // 添加一条数据发送到后端
      addGold() {
        console.log(this.list1);
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            let res = await this.$API.running.setGoldTable(this.list1);
            console.log(res);
            this.dialogFormVisible1 = false;
            this.getPageAccountDetailList()
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },
      // 获取某年某月的最后一天
      getLastDayOfMonth(year, month) {
        var date = new Date(year, month - 1, '01');
        //设置日期
        date.setDate(1);
        //设置月份
        date.setMonth(date.getMonth() + 1);
        //获取本月的最后一天
        var cdate = new Date(date.getTime() - 1000 * 60 * 60 * 24);
        //返回结果
        return cdate.getDate();
      },
      round(num, iCount = 2) {
        // iCount 保留几位小数
        let changeNum = num
        let zs = true
        // 判断是否是负数
        if (changeNum < 0) {
          changeNum = Math.abs(changeNum)
          zs = false
        }
        const iB = Math.pow(10, iCount)
        // 有时乘100结果也不精确
        const value1 = changeNum * iB
        let intDecSet = []
        let intDecHun = []

        let fValue = value1
        const value2 = value1.toString()
        const iDot = value2.indexOf('.')

        // 如果是小数
        if (iDot !== -1) {
          intDecSet = changeNum.toString().split('.')

          // 如果是科学计数法结果
          if (intDecSet[1].indexOf('e') !== -1) {
            return Math.round(value1) / iB
          }
          intDecHun = value2.split('.')

          if (intDecSet[1].length <= iCount) {
            return parseFloat(num, 10)
          }

          const fValue3 = parseInt(intDecSet[1].substring(iCount, iCount + 1), 10)

          if (fValue3 >= 5) {
            fValue = parseInt(intDecHun[0], 10) + 1
          } else {
            // 对于传入的形如111.834999999998 的处理（传入的计算结果就是错误的，应为111.835）
            if (fValue3 === 4 && intDecSet[1].length > 10 && parseInt(intDecSet[1].substring(iCount + 1, iCount + 2),
                10) === 9) {
              fValue = parseInt(intDecHun[0], 10) + 1
            } else {
              fValue = parseInt(intDecHun[0], 10)
            }
          }
        }
        // 如果是负数就用0减四舍五入的绝对值
        let val = zs ? (fValue / iB) : (0 - fValue / iB)

        const d = val.toString().split('.')
        if (d.length === 1) {
          return val.toString() + '.00'
        }
        if (d.length > 1) {
          if (d[1].length < 2) {
            val = val.toString() + '0'
          }
          return val
        }
      },
      rangeChange() {
        console.log('时间范围', this.valueData)
        if (!this.valueData) {
          this.valueData = []
        }
        this.getPageAccountDetailList()
      },
      handleExport2() {
        let auditResult = prompt('报表名字：');
        if (auditResult != null && auditResult != "") {
          exportToExcel('#table', auditResult);
        }
      },
      async getPageAccountDetailList() {
        let res = await this.$API.running.getGoldTable({
          // pageNumber: this.pageNumber,
          // pageSize: this.pageSize,
          // endTime: this.valueData[1],
          // startTime: this.valueData[0]
          month: this.valueData
        })
        // res.data[0].usableRate = this.toPercent(res.data[0].usableRate)
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].usableRate) {
            res.data[i].usableRate = this.toPercent(res.data[i].usableRate)
          }
        }
        console.log(res.data)
        this.list = this.list.concat(res.data)
      },
      handleSizeChange(val) {
        // console.log(`每页 ${val} 条`);
        this.pageSize = val
      },
      handleCurrentChange(val) {
        // console.log(`当前页: ${val}`);
        this.pageNumber = val
      },
      filterTag(value, row) {
        console.log(value, row)
        return row.operateType == value;
      }
    }
  }
</script>

<style>

</style>
